<?php
/**
 *
 *
 * @category     Shuxun Cms
 * @date         2015年10月25日
 * @author       Shuxun Team <kaiping.jiang@scshux.com>
 * @file         Acl.php
 */
namespace  Scshux\Plugin;
use Phalcon\Mvc\View;
use Phalcon\Di\FactoryDefault;
use Scshux\AbstractPlugin;
class Acl  extends AbstractPlugin
{
	protected $dispatcher = null;

	protected $view       = null;

	public  function __construct($dispatcher,$view)
	{

		$this->view = $view;
		$this->dispatcher = $dispatcher;

		$module = $dispatcher->getModuleName();
		$controller = $dispatcher->getControllerName();
		$action = $dispatcher->getActionName();
		if(empty($controller)){
			$controller = 'index';
		}
		if(empty($action)){
			$action = 'index';
		}

		$this->getDI()->get('view')->setVar('currentController',$controller);
		$this->getDI()->get('view')->setVar('currentAction',$action);
		$this->getDI()->get('view')->setVar('curentPageKey',$controller.'/'.$action);

		$identity = $this->getCore()->auth->getIdentity();
		$resourceKey = $module . '/' . $controller;

		$url = $this->getDI()->get('url')->get('login');
		if($identity < 1 && $resourceKey !='backend/login' && $module!='front'){
			$this->redirect($url);
		}

	}



	private function accessDenied($role, $resourceKey = null, $resourceVal = null)
	{
		$this->view->message = "$role - Access Denied to resource <b>$resourceKey::$resourceVal</b>";
		$this->view->partial('errors/err404');

		$response = new \Phalcon\Http\Response();
		$response->setHeader(403, 'Forbidden');
		$response->sendHeaders();
		echo $response->getContent();
		exit;
	}

	private function resourceNotFound($resourceKey)
	{

		$this->view->message = "Acl resource <b>$resourceKey</b> in <b>/app/config/acl.php</b> not exists";
		$this->view->partial('errors/err404');
		$response = new \Phalcon\Http\Response();
		$response->setHeader(404, 'Not Found');
		$response->sendHeaders();
		echo $response->getContent();
		exit;
	}

	private function redirect($url, $code = 302)
	{
		ob_clean();
		switch ($code) {
			case 301 :
				header('HTTP/1.1 301 Moved Permanently');
				break;
			case 302 :
				header('HTTP/1.1 302 Moved Temporarily');
				break;
		}
		header('Location: ' . $url);
		exit;
	}
}